package com.kang.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.boot.jackson.JsonComponent;

import java.io.IOException;
import java.text.ParseException;
import java.util.Date;

@JsonComponent
public class JsonDateDeserializer extends JsonDeserializer<Date> {
 private String[] patterns = {"yyyy-MM-dd HH:mm:ss","yyyy-MM-dd"};
 
 @Override
 public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException{
  String dateAsString = jsonParser.getText();
  Date parseDate = null;
  try {
   parseDate = DateUtils.parseDate(dateAsString, patterns);
  } catch (ParseException e) {
   throw new IllegalArgumentException(e.getCause());
  }
 
  return parseDate;
 }
}